package com.pdh.dao.Impl;

import com.pdh.dao.StudentDao;
import com.pdh.entity.Student;
import com.pdh.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: 彭_德华
 * @Date: 2021-09-15 19:38
 */
public class StudentDaoImpl implements StudentDao {
    // SQL 语句
    private static final String FIND_ALL = "SELECT * FROM STUDENT";

    /**
     * 查询所有student
     *
     * @return
     */
    @Override
    public List<Student> getAll() {
        List<Student> data = new ArrayList<>();
        Connection conn = null;
        PreparedStatement state = null;
        ResultSet result = null;
        try {
            conn = DruidUtil.getConnection();
            state = conn.prepareStatement(FIND_ALL);
            result = state.executeQuery();
            while (result.next()){
                Student s = new Student(result.getInt("id"),
                        result.getString("name"),
                        result.getInt("age"),
                        result.getString("sex")
                );
                data.add(s);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DruidUtil.close(conn,state,result);
        }
        return data;
    }
}
